package lab;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.databind.ObjectMapper;

public class ChatServlet extends HttpServlet {

    private final ObjectMapper jsonMapper = new ObjectMapper();

    private final ChatDataSource dataSource = new ChatDataSource("couchdb.properties");

    @Override
    public void init(ServletConfig config) throws ServletException {
        jsonMapper.setDateFormat(new SimpleDateFormat("yyyy-MM-dd,HH:mm"));
    }

    @Override
    public void destroy() {
        dataSource.shutdown();
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final Map<String, Object> result = new HashMap<String, Object>();
        result.put("msgHead", dataSource.currentMsgId());
        result.put("messages", dataSource.findMsgAfterCounter(Long.valueOf(request.getParameter("msgHead"))));
        jsonMapper.writeValue(response.getWriter(), result);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        final Map<String, String> params = jsonMapper.readValue(request.getReader(), Map.class);

        final ChatMessage newMsg = new ChatMessage(dataSource.currentMsgId() + 1, params.get("content"), new Date(), params.get("user"));
        dataSource.addMessage(newMsg);

        final Map<String, Object> result = new HashMap<String, Object>();
        result.put("msgHead", dataSource.currentMsgId());
        result.put("messages", dataSource.findMsgAfterCounter(Long.valueOf(String.valueOf(params.get("msgHead")))));
        jsonMapper.writeValue(response.getWriter(), result);
    }
}
